package msgbus

import "time"

type Token interface {
	Wait() bool
	WaitTimeout(time.Duration) bool
	Done()
	Error() error
}

type SSIoTToken struct {
	req      *MsgIoT
	ack      *MsgIoT
	complete chan struct{}
	err      error
	isDone   bool
}

func NewSSIoTToken() *SSIoTToken {
	iotToken = new(SSIoTToken)
	iotToken.complete = make(chan struct{})
	iotToken.isDone = false
	return iotToken
}

// Wait implements the Token Wait method.
func (this *SSIoTToken) Wait() bool {
	<-this.complete
	return true
}

// WaitTimeout implements the Token WaitTimeout method.
func (this *SSIoTToken) WaitTimeout(d time.Duration) bool {
	timer := time.NewTimer(d)
	select {
	case <-this.complete:
		if !timer.Stop() {
			<-timer.C
		}
		return true
	case <-timer.C:
	}

	return false
}

// Done implements the Token Done method.
func (this *SSIoTToken) Done() {
	if iotToken.isDone {
		return
	}
	iotToken.isDone = true
	close(this.complete)
}

func (this *SSIoTToken) Error() error {
	return this.err
}
